<?php

namespace App\Models\Base;

use App\Models\BaseModel;
use App\Params\Backend\ResourceListParam;
use App\Params\Backend\ResourceUpdateParam;
use Illuminate\Database\Eloquent\Model;

/**
 * 系统资源模型
 * 资源是绑定在二级菜单上面
 *
 * @package App\Models
 */
class Resource extends BaseModel
{
    protected $table = 'base_resource';
    protected $primaryKey = 'resource_id';

    /**
     * 根据菜单ID获取资源
     *
     * @param int $menuId
     * @param null $isActive
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function getByMenuId(int $menuId, $isActive = null)
    {
        $resource = Resource::query();
        if(!is_null($isActive)) {
            $resource->where('is_active', $isActive);
        }
        return $resource->where('menu_id', $menuId)->orderBy('sort_num', 'asc');
    }

    /**
     * 保存资源
     *
     * @param int $resourceId
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getById(int $resourceId)
    {
        return Resource::query()->where('resource_id', $resourceId)->first();
    }

    /**
     * 删除资源
     *
     * @param array $resIds
     * @return mixed
     */
    public static function remove(array $resIds)
    {
        return Resource::query()->whereIn('resource_id', $resIds)->delete();
    }

    /**
     * 停用/启用资源
     *
     * @param int $id
     * @param int $isActive
     * @return int
     */
    public static function enable(int $id, $isActive = 1)
    {
        return Resource::query()->where('resource_id', $id)->update(['is_active' => $isActive]);
    }

    /**
     * 删除菜单下的资源
     *
     * @param int $menuId
     * @return mixed
     */
    public static function removeByMenuId(int $menuId)
    {
        return Resource::query()->where('menu_id', $menuId)->delete();
    }

    /**
     * 获取资源列表
     *
     * @param ResourceListParam $param
     * @return
     */
    public static function getList(ResourceListParam $param)
    {
        $query = Resource::query()
            ->leftJoin('base_menu', 'base_resource.menu_id', '=', 'base_menu.menu_id')
            ->select('base_resource.*', 'base_menu.menu_name');
        if($param->getMenuId()) {
            $query->where('menu_id', $param->getMenuId());
        }
        if($param->getName()) {
            $query->where('resource_name', 'like', '%' . $param->getName() . '%');
        }
        return $query;
    }

    /**
     * 保存资源
     *
     * @param ResourceUpdateParam $param
     * @return int|mixed
     */
    public static function saveData(ResourceUpdateParam $param)
    {
        $query = $param->getResourceId() ? Resource::find($param->getResourceId()) : new Resource();
        foreach ($param as $key => $value) {
            $query->{$key} = $value;
        }
        return $query->save() ? $query->resource_id : 0;
    }
}
